import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class MagicSquares {
    public static boolean testMagic(String pathName) throws IOException {
        // Open the file
        BufferedReader reader = new BufferedReader(new FileReader(pathName));

        int lastSum = -1;
        
        // For each line in the file ...
        String line;
        ArrayList<ArrayList<Integer>> nums = new ArrayList<>();

        while ((line = reader.readLine()) != null) {
            // ... sum each row of numbers
            if(line.length() == 0)
                continue;
            nums.add(new ArrayList<Integer>());
            String[] parts = line.split("\t");
            for (String part : parts) {
                nums.getLast().add(Integer.parseInt(part));
            }
        }

        reader.close();

        // 横向
        for(ArrayList<Integer> number : nums){
            int sum = 0;
            for(int i:number){
                sum += i;
            }
            if(lastSum != -1){
                lastSum = sum;
            }else{
                if(lastSum != sum)
                    return false;
            }
        }

        // 竖向
        for(int i = 0; i < nums.size(); ++i){
            int sum = 0;
            for(int j = 0; j<nums.get(i).size(); ++j){
                sum += nums.get(i).get(j);
            }
            if(sum != lastSum)
                return false;
        }

        // 斜向
        int left_sum = 0, right_sum = 0;
        for(int i = 0; i < nums.size(); ++i){
            left_sum += nums.get(i).get(i);
            right_sum += nums.get(nums.size()-i-1).get(nums.size()-i-1);
            if(left_sum != lastSum || right_sum != lastSum || left_sum!=right_sum)
                return false;
        }

        return true;
    }

    public static void main(String[] args) throws IOException {
        String[] fileNames = { "Mercury.txt", "Luna.txt" };
        for (String fileName : fileNames) {
            System.out.println(fileName + " is magic? " + testMagic(fileName));
        }
    }
}
